import 'package:shared_preferences/shared_preferences.dart';
import 'package:fluttermodule/model/User.dart';
import 'dart:convert';
const ATUser  = "ATUserKey";
class MyUserTool{
  static void  getInstance(){
    SharedPreferences.setMockInitialValues({});
  }
  static Future <void> saveData(User user) async{
    try{
//      SharedPreferences.setMockInitialValues({});
      SharedPreferences prefs =  await SharedPreferences.getInstance();
      var encode = json.encode(user.toJson());
      print("encode = $encode");
      prefs.setString(ATUser, encode).then((success){
        print("saveData is success = $success");
      });
    }catch(e){
      print("error = $e");
    }
  }
  static Future <User>getData() async{
    try{
      print("-------------------------------------------------------");
//      SharedPreferences.setMockInitialValues({});
      SharedPreferences prefs = await SharedPreferences.getInstance();
      var decode =  prefs.getString(ATUser);
      print("decode = $decode");
      if (decode == null){
        return User();
      }
      Map<String ,dynamic> object = json.decode(decode);
      print("object is $object");
      User user = User.fromJson(object);
      String name = user.name;
      print("user name = $name");
      return user;
    } catch (e){
      print("error = $e");
    }
  }
  static Future <bool>delete() async{
//    SharedPreferences.setMockInitialValues({});
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool res = prefs.containsKey(ATUser);
    return await prefs.remove(ATUser);
  }

  static Future <bool>login() async{
    User user = await getData();
    if (user != null && user.token != null){
      return true;
    }
    return false;

  }
}
